<?php
/**
 * Created by PhpStorm.
 * User: xuke
 * Date: 16/6/21
 * Time: 上午9:40
 */

namespace App\Http\Model;


use App\Http\Models\GoodsSku;
use App\Exceptions\ApiException;

class Order extends Base
{
    public $table = 'order';
    
    protected $primaryKey = 'order_id';

    public function subOrder()
    {
        return $this->hasMany(OrderSub::class, 'order_id', 'order_id');
    }
    
    public function orderGoods()
    {
        return $this->hasMany(OrderGoods::class, 'order_id', 'order_id');
    }
    
    public function setUser($user_id)
    {
        $this->user_id = $user_id;
    }

    /**
     * 设置订单号
     */
    public function setOrderSn()
    {
        //用户流水号
        $user_serial = mt_rand(0,9).mt_rand(0,9).$this->user_id.mt_rand(0,9).mt_rand(0,9);

        //生成订单号,年月日时分秒+用户流水号
        $order_sn = date("YmdHis").$user_serial;
        $this->order_sn = $order_sn;
        return $this;
    }

    public function setSku($sku, $num)
    {
        if (is_numeric($sku))
        {
            $sku = GoodsSku::find($sku);
            if (empty($sku))
            {
                throw new ApiException(-2, '商品信息不存在');
            }
        }else if (!$sku instanceof GoodsSku)
        {
            throw new ApiException(-2, '商品参数信息错误');
        }
        $this->sku_id = $sku->sku_id;
        $this->goods_id = $sku->goods_id;
        $this->original_price = $sku->price;
        $this->goods_num = $num;
        $this->goods_sku_name = $sku->sku_name;
        return $this;
    }

}